package com.iw.core.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.iw.core.security.entity.Users;

/**
 * Servlet Filter implementation class UserFilter
 */
public class UserFilter implements Filter {

	public static Map<Integer, Map<HttpSession, Users>> loginedUserMap = new HashMap<Integer, Map<HttpSession, Users>>();

	/**
	 * Default constructor.
	 */
	public UserFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		// pass the request along the filter chain
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession currentSession = httpRequest.getSession();
		Users currentUser = (Users) currentSession.getAttribute("USER");
		if (currentUser != null) {
			Map<HttpSession, Users> uMap = loginedUserMap.get(currentUser.getId());
			if (uMap != null) {
				HttpSession session = uMap.keySet().iterator().next();
				if (currentSession.getCreationTime() < session.getCreationTime()) {
					currentSession = null;
					RequestDispatcher dispatcher = request.getRequestDispatcher("/repeat.jsp");
					dispatcher.forward(request, response);
					return;
				}
			}

		}

		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
